/*
 * $Id: MemoryPool.hpp 50 2009-02-10 05:48:05Z hyunghwan.chung $
 *
   Copyright 2005-2009 Chung, Hyung-Hwan.

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an  BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
 */

#ifndef _XP_BAS_MEMORYPOOL_CLASS_
#define _XP_BAS_MEMORYPOOL_CLASS_

#include <xp/types.h>
#include <xp/macros.h>
#include <xp/bas/assert.h>
#include <xp/Uncopyable.hpp>

XP_BEGIN_NAMESPACE2 (xp, bas)

//
// allocator for fixed-size data
//

class MemoryPool: public Uncopyable 
{
public:
	enum {
		DEFAULT_BLOCK_SIZE = 128
	};

	MemoryPool (
		xp_size_t datum_size, 
		xp_size_t block_size = DEFAULT_BLOCK_SIZE);
	~MemoryPool ();

	void* allocate ();
	void  dispose (void* ptr);
	void  dispose ();

	inline bool isEnabled () const
	{
		return this->datum_size > 0 && this->block_size > 0;
	}
	inline bool isDisabled () const
	{
		return this->datum_size <= 0 || this->block_size <= 0;
	}

	inline xp_size_t datumSize () const
	{
		return this->datum_size;
	}
	inline xp_size_t blockSize () const
	{
		return this->block_size;
	}
	inline void setBlockSize (xp_size_t blockSize) 
	{
		this->block_size = blockSize;
	}

	int swap (MemoryPool& mpool);

#ifdef XP_DEBUG_VERBOSE
	xp_size_t  nalloc;
	xp_size_t  navail;
#endif

protected:
	struct Block 
	{
		Block*  next;
		//xp_byte_t data[0];
	};
	struct Chain 
	{
		Chain* next;
	};

	Block* mp_blocks;
	Chain* free_list;
	xp_size_t datum_size;
	xp_size_t block_size;

	void add_block ();
};

XP_END_NAMESPACE2 (xp, bas)

#endif

